﻿Imports TBCC.UtilityMobile
Public Class TerminalAddNewForm

    Private _pi As ProjectItem

    Public Sub New(ByVal pi As ProjectItem)

        ' 此调用是 Windows 窗体设计器所必需的。
        InitializeComponent()

        ' 在 InitializeComponent() 调用之后添加任何初始化。
        _pi = pi
    End Sub

    Private Sub TerminalAddNewForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me.CenterToParent()

        If _pi.ProjectType >= 1 AndAlso _pi.ProjectType <= ProjectTypeList.GetLength(0) Then
            Me.txtNewPrjType.Text = ProjectTypeList(_pi.ProjectType - 1)
        Else
            Me.txtNewPrjType.Text = "未知终端"
        End If
    End Sub

    Private Sub btnNewPrj_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewPrj.Click

        _pi.ProjectName = Me.txtNewPrjName.Text
        Dim flag As Boolean

        If IsValidated() = True Then
            flag = Save()

            If flag = True Then
                msg.Show("增加终端成功。")
            Else
                msg.ShowError("增加终端失败。")
                Exit Sub
            End If

            Me.DialogResult = Windows.Forms.DialogResult.OK
            Me.Close()
        End If

    End Sub

    Private Sub btnNewCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnNewCancel.Click
        Me.DialogResult = Windows.Forms.DialogResult.Cancel
        Me.Close()
    End Sub

    Private Function IsValidated() As Boolean
        If Me.txtNewPrjName.Text.Trim.Length <= 0 Then
            msg.Show("终端名称不能为空。")
            Me.txtNewPrjName.Focus()
            Return False
        End If

        Dim pi As ProjectItem
        For Each row As DataGridViewRow In MainForm.ProjectList.Values
            pi = row.Tag
            If pi IsNot Nothing AndAlso pi.ProjectName.Equals(Me.txtNewPrjName.Text) = True Then
                msg.Show(String.Format("终端名称 ""{0}"" 已经存在。", Me.txtNewPrjName.Text))
                Me.txtNewPrjName.Focus()
                Return False
            End If
        Next

        Return True
    End Function

    Private Function Save() As Boolean

        Dim flag As Boolean
        Try
            flag = ProjectService.CreateBasicInfo(_pi)
            If flag = True Then
                flag = False
                Dim dti As DevTypeItem = ProjectBasicInfoForm.CreateDevTypeItem(_pi)
                flag = ProjectService.AddDevRefTypeList(dti, 0, _pi.ProjectType)
            End If
        Catch ex As Exception
            msg.ShowError(ex.Message)
            Return False
        End Try

        Return flag
    End Function

End Class